<template>
  <div class="column-detail-page">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 专栏信息 -->
    <div v-else-if="column" class="column-container">
      <!-- 专栏头部 -->
      <div class="column-header">
        <!-- 专栏标题 -->
        <div class="column-title-section">
          <h1 class="column-name">{{ column.name }}</h1>
        </div>

        <!-- 专栏封面 -->
        <div class="column-cover">
          <img
            v-if="column.coverImage"
            :src="getMediaUrl(column.coverImage)"
            :alt="column.name"
            class="cover-image"
          />
          <div v-else class="default-cover">
            <el-icon size="64"><Notebook /></el-icon>
          </div>
        </div>

        <!-- 专栏信息 -->
        <div class="column-info">
          <div class="column-meta">
            <p class="column-description" v-if="column.description">
              {{ column.description }}
            </p>

            <!-- 作者信息 -->
            <div class="author-info">
              <el-avatar
                :size="40"
                :src="getMediaUrl(column.userAvatar)"
                class="author-avatar"
              >
                {{ column.userNickname?.charAt(0) }}
              </el-avatar>
              <div class="author-details">
                <div class="author-name">{{ column.userNickname }}</div>
                <div class="author-title">Columnist</div>
              </div>
            </div>

            <!-- 统计信息 -->
            <div class="column-stats">
              <div class="stat-item">
                <span class="stat-number">{{ formatCount(column.articleCount || 0) }}</span>
                <span class="stat-label">Article</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ formatCount(column.followerCount || 0) }}</span>
                <span class="stat-label">People follow</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="column-actions">
            <el-button
              v-if="!isOwner"
              :type="column.isFollowed ? 'default' : 'primary'"
              size="large"
              @click="handleFollow"
              :loading="followLoading"
            >
              {{ column.isFollowed ? 'Followed' : 'Follow the column' }}
            </el-button>

            <el-dropdown v-if="isOwner" trigger="click">
              <el-button type="primary" size="large">
                管理专栏
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="showEditDialog = true">
                    <el-icon><Edit /></el-icon>
                    编辑专栏
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleDelete" divided>
                    <el-icon><Delete /></el-icon>
                    删除专栏
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>

      <!-- 专栏内容 -->
      <div class="column-content">
        <!-- 文章列表 -->
        <div class="articles-section">
          <div class="section-header">
            <h2 class="section-title">Column article</h2>
            <div class="section-actions">
              <el-select
                v-model="sortType"
                placeholder="Sort by"
                class="sort-select"
                @change="handleSortChange"
              >
                <el-option label="Latest release" :value="1" />
                <el-option label="Earliest release" :value="2" />
              </el-select>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="articlesLoading" class="articles-loading">
            <el-skeleton :rows="5" animated />
          </div>

          <!-- 文章列表 -->
          <div v-else-if="articles.length > 0" class="articles-list">
            <ContentCard
              v-for="article in articles"
              :key="article.id"
              :data="transformArticleData(article)"
            />
          </div>

          <!-- 空状态 -->
          <div v-else class="empty-articles">
            <el-empty
              :image-size="120"
              description="No article"
            >
              <template #image>
                <el-icon size="120" color="#d3d3d3"><Document /></el-icon>
              </template>
            </el-empty>
          </div>

          <!-- 分页 -->
          <div v-if="articlesTotal > 0" class="pagination-container">
            <el-pagination
              v-model:current-page="articlesPagination.pageNum"
              v-model:page-size="articlesPagination.pageSize"
              :total="articlesTotal"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleArticlesSizeChange"
              @current-change="handleArticlesCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-state">
      <el-empty
        :image-size="120"
        description="Column does not exist or has been deleted"
      >
        <template #image>
          <el-icon size="120" color="#d3d3d3"><WarningFilled /></el-icon>
        </template>
        <el-button type="primary" @click="$router.push('/column')">
          go back to column list
        </el-button>
      </el-empty>
    </div>

    <!-- 编辑专栏对话框 -->
    <EditColumnDialog
      v-model="showEditDialog"
      :column="column"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref, watch} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {ArrowDown, Delete, Document, Edit, Notebook, WarningFilled} from '@element-plus/icons-vue'
import ContentCard from '@/views/home/components/ContentCard.vue'
import EditColumnDialog from './components/EditColumnDialog.vue'
import {deleteColumn, getColumnArticles, getColumnDetail, toggleFollowColumn} from '@/api/column'
import {getMediaUrl} from '@/utils/media'
import {formatCount} from '@/utils/format'
import {useUserStore} from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const articlesLoading = ref(false)
const followLoading = ref(false)
const column = ref(null)
const articles = ref([])
const articlesTotal = ref(0)
const sortType = ref(1) // 默认最新发布
const showEditDialog = ref(false)

const articlesPagination = reactive({
  pageNum: 1,
  pageSize: 20
})

// 计算属性
const isOwner = computed(() => {
  return userStore.isLoggedIn && column.value && userStore.userInfo?.userId === column.value.userId
})

// 生命周期
onMounted(() => {
  loadColumnDetail()
})

// 监听路由参数变化
watch(
  () => route.params.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) {
      loadColumnDetail()
    }
  }
)

// 方法
const loadColumnDetail = async () => {
  const columnId = route.params.id
  if (!columnId) {
    router.push('/column')
    return
  }

  loading.value = true
  try {
    const response = await getColumnDetail(columnId)
    if (response.code === 200) {
      column.value = response.data
      loadColumnArticles()
    } else {
      ElMessage.error(response.message || '获取专栏详情失败')
    }
  } catch (error) {
    console.error('获取专栏详情失败:', error)
    ElMessage.error('获取专栏详情失败')
  } finally {
    loading.value = false
  }
}

const loadColumnArticles = async () => {
  if (!column.value) return

  articlesLoading.value = true
  try {
    const params = {
      pageNum: articlesPagination.pageNum,
      pageSize: articlesPagination.pageSize
    }

    const response = await getColumnArticles(column.value.id, params)
    if (response.code === 200) {
      articles.value = response.data.data || []
      articlesTotal.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取专栏文章失败')
    }
  } catch (error) {
    console.error('获取专栏文章失败:', error)
    ElMessage.error('获取专栏文章失败')
  } finally {
    articlesLoading.value = false
  }
}

const handleFollow = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  followLoading.value = true
  try {
    const response = await toggleFollowColumn(column.value.id)
    if (response.code === 200) {
      column.value.isFollowed = response.data
      if (response.data) {
        column.value.followerCount = (column.value.followerCount || 0) + 1
        ElMessage.success('Followed successfully')
      } else {
        column.value.followerCount = Math.max(0, (column.value.followerCount || 0) - 1)
        ElMessage.success('Unfollowed')
      }
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('关注专栏失败:', error)
    ElMessage.error('操作失败')
  } finally {
    followLoading.value = false
  }
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      '删除后专栏将无法恢复，确定要删除这个专栏吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await deleteColumn(column.value.id)
    if (response.code === 200) {
      ElMessage.success('专栏删除成功')
      router.push('/column')
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除专栏失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleEditSuccess = () => {
  showEditDialog.value = false
  loadColumnDetail()
}

const handleSortChange = () => {
  articlesPagination.pageNum = 1
  loadColumnArticles()
}

const handleArticlesSizeChange = (size) => {
  articlesPagination.pageSize = size
  articlesPagination.pageNum = 1
  loadColumnArticles()
}

const handleArticlesCurrentChange = (page) => {
  articlesPagination.pageNum = page
  loadColumnArticles()
}

// 转换文章数据格式以适配 ContentCard 组件
const transformArticleData = (article) => {
  return {
    id: article.id,
    type: 'article',
    title: article.title,
    content: article.summary || article.content,
    author: {
      id: article.userId,
      name: article.userNickname,
      avatar: article.userAvatar
    },
    publishTime: article.publishTime || article.createdTime,
    stats: {
      viewCount: article.viewCount,
      likeCount: article.likeCount,
      commentCount: article.commentCount,
      collectCount: article.collectCount
    },
    isLiked: article.isLiked,
    isCollected: article.isCollected,
    tags: []
  }
}
</script>

<style lang="scss" scoped>
.column-detail-page {
  min-height: 100vh;
  background: $background-light;
}

.loading-container {
  padding: 40px;
  max-width: 1200px;
  margin: 0 auto;
}

.column-container {
  max-width: 1200px;
  margin: 0 auto;
}

.column-header {
  background: white;
  padding: 40px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  border-bottom: 1px solid $border-light;

  .column-title-section {
    text-align: center;

    .column-name {
      font-size: 32px;
      font-weight: 700;
      color: $text-color;
      margin: 0;
      line-height: 1.2;
    }
  }

  .column-cover {
    display: flex;
    justify-content: center;
    margin: 16px 0;

    .cover-image {
      width: 400px;
      height: 240px;
      object-fit: cover;
      border-radius: $border-radius-medium;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .default-cover {
      width: 400px;
      height: 240px;
      background: linear-gradient(135deg, $primary-color, #40a9ff);
      border-radius: $border-radius-medium;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .column-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;

    .column-meta {
      max-width: 600px;
      margin: 0 auto;

      .column-description {
        font-size: 16px;
        color: $text-secondary;
        line-height: 1.6;
        margin: 0 0 24px 0;
        text-align: center;
      }

      .author-info {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        margin-bottom: 24px;

        .author-avatar {
          background: linear-gradient(135deg, $primary-color, #40a9ff);
          color: white;
          font-weight: 600;
          flex-shrink: 0;
        }

        .author-details {
          .author-name {
            font-size: 16px;
            font-weight: 600;
            color: $text-color;
            margin-bottom: 2px;
          }

          .author-title {
            font-size: 14px;
            color: $text-secondary;
          }
        }
      }

      .column-stats {
        display: flex;
        justify-content: center;
        gap: 32px;

        .stat-item {
          display: flex;
          flex-direction: column;
          align-items: center;

          .stat-number {
            font-size: 24px;
            font-weight: 700;
            color: $text-color;
            line-height: 1;
          }

          .stat-label {
            font-size: 14px;
            color: $text-secondary;
            margin-top: 4px;
          }
        }
      }
    }

    .column-actions {
      display: flex;
      justify-content: center;
      gap: 16px;
      margin-top: 16px;
    }
  }
}

.column-content {
  background: white;

  .articles-section {
    padding: 32px 40px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;

      .section-title {
        font-size: 20px;
        font-weight: 600;
        color: $text-color;
        margin: 0;
      }

      .sort-select {
        width: 140px;
      }
    }

    .articles-loading {
      margin: 20px 0;
    }

    .articles-list {
      display: flex;
      flex-direction: column;
      gap: 16px;
      margin-bottom: 32px;
    }

    .empty-articles {
      text-align: center;
      padding: 60px 20px;
    }

    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 32px;
    }
  }
}

.error-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
  padding: 40px;
}

// 响应式设计
@media (max-width: 768px) {
  .column-header {
    flex-direction: column;
    padding: 24px 16px;
    gap: 24px;

    .column-cover {
      align-self: center;

      .cover-image,
      .default-cover {
        width: 200px;
        height: 120px;
      }
    }

    .column-info {
      .column-meta {
        .column-name {
          font-size: 24px;
        }

        .column-stats {
          gap: 24px;
          justify-content: center;
        }
      }

      .column-actions {
        justify-content: center;
      }
    }
  }

  .column-content .articles-section {
    padding: 24px 16px;

    .section-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .sort-select {
        width: 100%;
      }
    }
  }
}
</style>
